package com.qf.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.bean.JsonResult;
import com.qf.pojo.Announcement;
import com.qf.service.AnnouncementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.List;

@RequestMapping("announcement")
@Controller
public class AnnouncementController {

    @Autowired
    private AnnouncementService announcementService;

    @RequestMapping("findByPage")
    @ResponseBody
    public JsonResult findByPage(
            @RequestParam(value = "page", required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(value = "limit", required = false, defaultValue = "5") Integer pageSize) {

        JsonResult jsonResult = JsonResult.ok();

        PageHelper.startPage(pageNum, pageSize);

        List<Announcement> list = announcementService.findAll();
//        System.out.println(list);

        PageInfo<Announcement> pageInfo = new PageInfo<>(list);

        jsonResult.setCount(pageInfo.getTotal());
        jsonResult.setData(pageInfo.getList());

//        System.out.println(jsonResult.getData());

        return jsonResult;
    }

    @RequestMapping("deleteAll")
    @ResponseBody
    public String deleteAll(Integer[] id) {
//        System.out.println(Arrays.toString(id));

        announcementService.deleteAll(id);

        return "success";
    }

    @RequestMapping("deleteById")
    @ResponseBody
    public String deleteById(Integer id) {

//        System.out.println(id);

        announcementService.deleteById(id);

        return "success";
    }

    @RequestMapping("updateAnnouncement")
    @ResponseBody
    public String updateAnnouncement(Announcement announcement) {

        announcementService.updateAnnouncemet(announcement);

        return "success";
    }

    @RequestMapping("addAnnouncement")
    public String addAnnouncement(Announcement announcement) {

        announcementService.addAnnouncement(announcement);

        return "redirect:/index.html";
    }
}
